package com.sky.service.impl;

import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private ReportService reportService;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverReportVO(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        // 获取营业额列表
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList){
            //根据日期查询营业额，订单状态为5
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            long status = 5;
            Double result = reportMapper.getTurnover(beginTime, endTime, status);
            double turnover = 0.0;
            if (result != null) {
                turnover = result.doubleValue();
                // 使用 turnover 进行后续操作
            }
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserReportVO(LocalDate begin, LocalDate end) {
        // 获得日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        // 获取用户总量表
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            //根据日期查询用户总量
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalUser = reportMapper.getTotalUser(endTime);
            totalUserList.add(totalUser);
        }
        // 获取新增用户表
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            //根据日期查询用户总量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser = reportMapper.getNewUser(beginTime, endTime);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO getOrderReportVO(LocalDate begin, LocalDate end) {
        // 获得日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        // 获取每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            //根据日期查询订单总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = reportMapper.getOrderCount(beginTime, endTime);
            orderCountList.add(orderCount);
        }
        // 获取每日有效订单数量 status-5-已完成
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            //根据日期查询订单总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer validOrderCount = reportMapper.getValidOrderCount(beginTime, endTime, 5);
            validOrderCountList.add(validOrderCount);
        }
        // 获取订单总数
        LocalDateTime origin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime nowaday = LocalDateTime.of(end, LocalTime.MAX);
        Integer totalOrderCount = reportMapper.getOrderCount(origin, nowaday);
        // 获取有效订单总数
        Integer validOrderCount = reportMapper.getValidOrderCount(origin, nowaday, 5);
        // 计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 ) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        // 获取top10名称列表
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<String> nameList = reportMapper.getSalesTop10Name(beginTime, endTime);
        // 获取top10销量列表
        List<String> numberList = reportMapper.getSalesTop10Number(beginTime, endTime);
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1.获取数据库30天运营数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        // 2.将POI数据写入Excel文件
        InputStream example = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于模板创建一个新的Excel文件
            XSSFWorkbook workbook = new XSSFWorkbook(example);
            // 获取表格文件的sheet页
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            // 填充数据-时间
            sheet.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end);
            // 获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            // 获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                // 查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                // 获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            // 3.将Excel文件输出到客户端
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);

            // 关闭资源
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        // 获得日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
